﻿using System;
using System.Diagnostics;
using System.Text;

namespace WebHelper.Helpers
{
    [Serializable]
    public class HexaDecimalHelper
    {
        public static string Encode(byte[] data)
        {
            StringBuilder results = new StringBuilder();
            foreach (byte b in data)
            {
                results.Append(b.ToString("X2"));
            }

            //trace
            Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Encoded : " + getBytesAsString(data) + "--->" + results.ToString(), typeof(HexaDecimalHelper).Name + "  ");

            return results.ToString();
        }
        public static byte[] Decode(string data)
        {
            // GetString encodes the hex numbers with two digits
            byte[] results = new byte[data.Length / 2];
            for (int i = 0; i < data.Length; i += 2)
            {
                results[i / 2] = Convert.ToByte(data.Substring(i, 2), 16);
            }

            //trace
            Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Encoded : " + data + "--->" + getBytesAsString(results), typeof(HexaDecimalHelper).Name + "  ");

            return results;
        }


        //trace 
        private static string getBytesAsString(byte[] bytes)
        {
            string s="";
            for (int i = 0; i < bytes.Length; i++)
			{
                s += bytes[i] + ",";
			}
            if (s.EndsWith(","))
            {
                s = s.Substring(0, s.Length - 1);
            }
            return s;
        }
    }
}